package com.bizframework.core.util;

import java.util.HashMap;
import java.util.List;

import com.bizframework.core.domain.BaseEntity;


public class EntityUtils {

	public static <T extends BaseEntity<?>, IDT> T getEntityFromListById(
			List<T> list, IDT id) {
		for (T t : list) {
			if (t.getId().equals(id)) {
				return t;
			}
		}
		return null;
	}

	public static <T extends BaseEntity<?>> void updateEntityListProperty(
			List<T> sourceList, List<T> newList) {

		if (sourceList == null) {
			return;
		}

		if (newList == null) {
			return;
		}
		HashMap<String, T> sourceMap = new HashMap<String, T>();
		for (T t : sourceList) {
			if (t.getId() != null && t.getId().toString() != "") {
				sourceMap.put(t.getId().toString(), t);
			}
		}

		sourceList.clear();
		HashMap<String, T> newMap = new HashMap<String, T>();
		for (T t : newList) {
			if (t.getId() != null && t.getId().toString() != "") {
				newMap.put(t.getId().toString(), t);
			} else {
				sourceList.add(t);
			}
		}

		for (T t : newMap.values()) {
			if (t.getId() == null) {
				sourceList.add(t);
			} else if (t.getId() == "") {
				sourceList.add(t);
			} else if (sourceMap.containsKey(t.getId().toString())) {
				sourceList.add(sourceMap.get(t.getId().toString()));
			} else {
				sourceList.add(t);
			}
		}
	}
}
